package com.salmon.oss.controller;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.ExecutorService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.salmon.oss.cache.CacheUtils;
import com.salmon.oss.common.AjaxResult;
import com.salmon.oss.common.StringUtil;
import com.salmon.oss.common.UploadUtils;
import com.salmon.oss.entity.Peers;
import com.salmon.oss.properties.AdminProperties;
import com.salmon.oss.thread.InsertLevelDB;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import static com.salmon.oss.controller.LevelDBController.FASTDFS_SERVER_ADDRESS;

@RestController
@RequestMapping({"/file"})
@CrossOrigin(
        maxAge = 3600L
)
public class FileController {
    @Resource
    private AdminProperties adminProperties;
    @Resource
    private CacheUtils cacheUtils;
    private ExecutorService executorService = ThreadUtil.newExecutor(10);

    public FileController() {
    }

    @PostMapping({"/upload"})
    public AjaxResult moreFileUpload(@RequestParam("file") MultipartFile file, @RequestParam(defaultValue = "default") String scene, @RequestParam(defaultValue = "") String path) {
        if (file.isEmpty()) {
            return new AjaxResult(500, "请选择文件");
        } else if (StringUtil.isBlank(scene)) {
            return new AjaxResult(500, "请填写上传场景");
        } else {
            Peers peers = this.cacheUtils.get(FASTDFS_SERVER_ADDRESS);
            AjaxResult result = UploadUtils.upload(this.adminProperties.getUpload_temp_path(), peers.getServerAddress() + "/" + peers.getGroupName() + "/upload", path, scene, file, peers.getServerAddress());
            this.executorService.submit(new InsertLevelDB(this.cacheUtils.getLevelDB(), result.getData()));
            return result;
        }
    }

    @GetMapping({"/downloadFile"})
    public void downloadFile(String path, String name, HttpServletResponse response) {
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
        response.setContentType("application/octet-stream");
        BufferedInputStream in = null;
        try {
            Peers peers = this.cacheUtils.get(FASTDFS_SERVER_ADDRESS);
            URL url = new URL(peers.getServerAddress() + "/" + peers.getGroupName() + "/" + path + "/" + name);
            in = new BufferedInputStream(url.openStream());
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
            int i;
            while((i = in.read()) != -1) {
                response.getOutputStream().write(i);
            }
            response.getOutputStream().close();
        } catch (IOException var16) {
            var16.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException var15) {
                var15.printStackTrace();
            }
        }
    }

    @GetMapping({"/download"})
    public ResponseEntity<Object> getFile(String path, String name) throws IOException {
        Peers peers = this.cacheUtils.get(FASTDFS_SERVER_ADDRESS);
        URL url = new URL(peers.getServerAddress() + "/" + peers.getGroupName() + "/" + path + "/" + name);
        HttpHeaders headers = new HttpHeaders();
        org.springframework.core.io.Resource resource = new InputStreamResource(url.openStream());
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(name, "UTF-8"));
        return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
    }

    @GetMapping({"/download/{md5}"})
    public ResponseEntity<Object> getFile(@PathVariable String md5) throws IOException {
        String downLoadUrl = this.cacheUtils.getFromDB(md5);
        if (StrUtil.isBlank(downLoadUrl)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(new AjaxResult(HttpStatus.NOT_FOUND.value(), "未找到要下载的文件"));
        } else {
            URL url = new URL(downLoadUrl);
            int index = downLoadUrl.lastIndexOf("/");
            String fileName = downLoadUrl.substring(index + 1);
            HttpHeaders headers = new HttpHeaders();
            org.springframework.core.io.Resource resource = new InputStreamResource(url.openStream());
            headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8"));
            return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
        }
    }
}
